// server/middleware/tenant.js
import {getTenantByHost, getTenantBySubdomain} from "~/server/utils/tenant.js";

export default defineEventHandler(async (event) => {
    const host = event.node.req.headers.host;

    // 提取主域名和二级域名
    const domainParts = host.split('.');
    let tenant;

    if (domainParts.length === 2) {
        // 假设自定义域名，查找该域名的租户
        tenant = await getTenantByHost(host);
        console.info("host2", host)
    } else if (domainParts.length === 3) {
        // 假设是二级域名的方式，如 tenant1.saas.com
        const subdomain = domainParts[0];
        console.info("host3", host)
        tenant = await getTenantBySubdomain(subdomain);
    }else{
        console.info("host4", host)
    }

    if (!tenant) {
        tenant=1;
    }

    // 将租户信息挂载到事件对象
    event.context.tenant = tenant;
});
